package survey;

import java.util.PriorityQueue;
import util.Picture;

/**
 * The thread SurveyController receives different pictures and sorts them in a
 * Queue.
 */
public class Synchronizer {
	private PriorityQueue<Picture> q;
	private int limit;
	private boolean on = true;

	public Synchronizer() {
		q = new PriorityQueue<Picture>();
		limit = 500;
	}

	/**
	 * Inserts a picture to the queue for sorting and notify all.
	 * 
	 * @param p
	 *            picture which should be sorted and shown
	 */
	public synchronized void insertPicture(Picture p) {
		q.add(p);
		notifyAll();
	}
	
	synchronized void turnOff() {
		on = false;
		notifyAll();
	}

	/**
	 * Synchronize all picture by waiting 500 ms until showing pictures.
	 * Pictures are shown by the : (500 ms - (CurrentTime - PictureTakenTime)).
	 * Anytime a new picture is added to the queue the method rechecks if the
	 * latest should be displayed before the current.
	 * 
	 * @return picture to be displayed, null if interrupted
	 */
	public synchronized Picture getPicture() throws InterruptedException {
		while (on && q.isEmpty()) {
			wait();
		}

		while (on && limit >= q.peek().getDelay()) {
				long waitTime = limit - q.peek().getDelay();
				if (on && waitTime > 0) {
					wait(waitTime);
				}
		}

		if (on && limit < 0)
			q.peek().setSync(false);

		return q.poll();
	}

	/**
	 * Use for forced Asynchronous mode
	 */
	public synchronized void setAsync() {
		limit = Integer.MIN_VALUE;
	}

	/**
	 * Use for forced Synchronous mode
	 */
	public synchronized void setSync() {
		limit = 500;
	}

}
